import {uuid} from './utils';
import {saleOrderStatus} from '../Enum';
import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE, DEFAULT_QUERY_OPTION} from './constants';
import * as api from './api';
import moment from 'moment';

export const ERROR_CODE = 'error';
/*==============================查询action================================= */
//修改查询条件
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});


//重置查询条件
export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => (dispatch, getState) => {
    const {isDealerUser} = getState().getIn(['page', 'domainData', 'initData']).toJS();
    const data = isDealerUser ? DEFAULT_QUERY_OPTION : {
        ...DEFAULT_QUERY_OPTION,
        status: [saleOrderStatus.确认通过]
    };
    return dispatch({
        type: RESET_QUERY_PANEL,
        data
    });
};

/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = (data, conditions) => ({
    type: GET_INIT_SUCCESS,
    data,
    conditions
});
export const getInitDataFail = message => ({
    type: GET_INIT_FAIL,
    message
});

//获取初始化数据和权限
export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok) {
            const {isDealerUser} = res.data;
            const condition = isDealerUser ? {} : {
                status: [saleOrderStatus.确认通过]
            };
            dispatch(getInitDataSuccess(res.data, condition));
        }
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};

/*==============================查询列表================================= */
export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = message => ({
    type: GET_LIST_FAIL,
    message
});

//获取列表
export const getList = condition => dispatch => {
    dispatch(getListBegin());
    const {createTime, ...props} = condition;

    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    return api.getPartSaleOrders(props).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
    });
};

//按钮搜索
export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getList(condition));
};

//分页排序搜索
export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

//导出
export const onClickExport = () => (dispatch, getState) => {
    const {pageIndex, pageSize, isDesc, sortField, createTime, ...props} = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS() || {};
    if(createTime && createTime.length > 0) {
        props.beginCreateTime = moment(createTime[0]).toISOString();
        props.endCreateTime = moment(createTime[1]).toISOString();
    }
    return api.exportPartSaleOrders(props);
};

export const GET_WAREHOUSE_SUCCESS = 'GET_WAREHOUSE_SUCCESS';

export const getWarehouseSuccess = data => ({
    type: GET_WAREHOUSE_SUCCESS,
    data,
});
//获取加价率
export const GET_RAISINGRATE_SUCCESS = 'GET_RAISINGRATE_SUCCESS';
export const getRaisingRateSuccess = data => ({
    type: GET_RAISINGRATE_SUCCESS,
    data
});
export const GET_RAISINGRATE_FAIL = 'GET_RAISINGRATE_FAIL';
export const getRaisingRateFail = data => ({
    type: GET_RAISINGRATE_FAIL,
    data
});
export const getRaisingRate = () => (dispatch, getState) => {
    const {dealerId, typeId} = getState().getIn(['page', 'appState', 'submitData']).toJS();
    return api.getRaisingRate(dealerId, typeId)
        .then(res => {
            if(res.ok) {
                const {isDealerUser} = getState().getIn(['page', 'domainData', 'initData']).toJS() || {};
                const {warehouses, ...props} = res.data;
                if(!isDealerUser)
                    dispatch(getWarehouseSuccess(warehouses));
                dispatch(getRaisingRateSuccess(props));
            } else
                dispatch(getRaisingRateFail());
            return res.ok;
        });
};

/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

//获取详情
export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getPartSaleOrdersDetail(id).then(res => {
        if(res.ok) {
            const {details = [], ...props} = res.data;
            dispatch(
                getDetailSuccess({
                    ...props,
                    details: details.map(item => ({
                        id: uuid(),
                        ...item
                    })),
                })
            );
            const {dealerId, typeId} = props;
            return api.getRaisingRate(dealerId, typeId)
                .then(resp => {
                    if(resp.ok) {
                        const {warehouses} = resp.data;
                        dispatch(getWarehouseSuccess(warehouses));
                    }
                    return resp.ok;
                });
        }
        return res.ok;
    });
};

export const onClickSubmit = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.submitPartSaleOrders(id, {
        rowVersion
    });
};
export const onClickSubmitForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.submitPartSaleOrders(id, {
        rowVersion
    });
};
export const onClickReturnOrder = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    const {rowVersion, remark} = data;
    return api.returnPartSaleOrders(id, {
        remark,
        rowVersion
    });
};

/*=============================作废/代作废================================== */
export const onClickAbandon = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.abandonPartSaleOrders(id, {
        rowVersion
    });
};
export const onClickAbandonForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.abandonPartSaleOrders(id, {
        rowVersion
    });
};


/*=============================确认================================== */
export const onClickConfirm = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.confirmPartSaleOrders(id, {
        rowVersion
    });
};
export const onClickConfirmForDetail = id => (dispatch, getState) => {
    const {rowVersion} = getState()
        .getIn(['page', 'domainData', 'detail', 'data'])
        .toJS();
    return api.confirmPartSaleOrders(id, {
        rowVersion
    });
};


/*==============================初始化或清理数据================================= */
//清除数据
export const CLEAR_DATA = 'CLEAR_DATA';
export const clearData = () => ({
    type: CLEAR_DATA
});

/*==============================新增修改action================================= */
//修改提交信息
export const SAVE_SUBMIT_CONDITION = 'SAVE_SUBMIT_CONDITION';
export const saveEditCondition = (name, value) => ({
    type: SAVE_SUBMIT_CONDITION,
    name,
    value
});
export const onSubmit = id => (dispatch, getState) => {
    const {details = [], dealerId, brandId, typeId, requiredArrivedDate, remark, rowVersion, warehouseId} = getState()
        .getIn(['page', 'appState', 'submitData'])
        .toJS();
    const brands = getState().getIn(['page', 'domainData', 'initData', 'brands']).toJS() || [];
    const detailData = details.map(item => ({
        partId: item.partId,
        planQuantity: item.planQuantity
    }));
    if(id)
        return api.updatePartSaleOrders(id, {
            details: detailData,
            requiredArrivedDate,
            typeId,
            remark,
            warehouseId,
            rowVersion,
            brandId
        });
    const defalutBrandId = brands.length === 1 ? brands[0].id : '';
    return api.addPartSaleOrders({
        brandId: brandId || defalutBrandId,
        details: detailData,
        dealerId,
        typeId,
        requiredArrivedDate,
        warehouseId,
        remark
    });
};
export const SELECT_MODAL_DATA = 'SELECT_MODAL_DATA';
export const selectModalData = data => ({
    type: SELECT_MODAL_DATA,
    data
});
export const selectDealer = data => dispatch =>
    dispatch(
        selectModalData({
            dealerId: data.id,
            dealerCode: data.code,
            dealerName: data.name,
            warehouseName: '',
            raisingRate: 0
        })
    );
export const selectType = data => dispatch =>
    dispatch(
        selectModalData({
            typeId: data.id,
            typeName: data.typeName,
            creditCode: data.creditCode,
            creditDescribe: data.creditDescribe,
            orderReasonCode: data.orderReasonCode,
            orderReason: data.orderReason,
            details: [],
            raisingRate: 0,
            warehouseName: ''
        })
    );
export const saveSubmitCondition = (name, value) => (dispatch, getState) => {
    if(name !== 'typeId') return dispatch(saveEditCondition(name, value));
    const types =
        getState()
            .getIn(['page', 'domainData', 'initData', 'types'])
            .toJS() || [];
    const data = types.find(item => item.id === value) || {};
    return dispatch(selectType(data));
};
export const DELETE_DETAIL = 'DELETE_DETAIL';
export const deleteDetail = id => ({
    type: DELETE_DETAIL,
    id
});
export const DELETE_ALL_DETAIL = 'DELETE_ALL_DETAIL';
export const deleteAllDetail = () => ({
    type: DELETE_ALL_DETAIL
});
export const UPDATE_DETAIL = 'UPDATE_DETAIL';
export const updateDetail = data => ({
    type: UPDATE_DETAIL,
    data
});
export const SELECT_DETAIL_FOR_PARTS = 'SELECT_DETAIL_FOR_PARTS';

const selectDetailForParts = data => ({
    type: SELECT_DETAIL_FOR_PARTS,
    data
});

export const selectPart = data => dispatch => {
    const parts = data.map(item => ({
        partId: item.id,
        partCode: item.code,
        partName: item.name,
        unit: item.unit,
        planQuantity: 1,
        taxPrice: item.wholeSalePrice,
        minPackSize: item.minPackSize
    }));
    return dispatch(selectDetailForParts(parts));
};

export const getParts = condition => (dispatch, getState) => {
    const {typeId} = getState().getIn(['page', 'appState', 'submitData']).toJS();
    return api.getParts({
        ...condition,
        typeId
    });
};

export const ADD_INIT = 'ADD_INIT';
export const addInit = () => (dispatch, getState) => {
    const {enterprise = {}, isDealerUser} = getState().getIn(['page', 'domainData', 'initData']).toJS() || {};
    if(isDealerUser)
        return dispatch({
            type: ADD_INIT,
            data: enterprise
        });
    return null;
};
